package com.uh.microservice.core.controller;

import com.uh.microservice.core.CONSTANTS;
import com.uh.microservice.core.dto.RspBody;
import com.uh.microservice.core.spring.SpringUtil;
import com.uh.microservice.core.spring.mvc.ThreadVariable;
import com.uh.microservice.core.util.JSONParser;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller的基类
 * 提供常用方法供子Controller使用
 * Created by liming on 2017/9/15.
 */
public class BaseSupport {

    /**
     * 获取全局统一配置的日期格式，
     *    以便按统一的格式返回给前端
     */
    public String getDataformat() {
        return SpringUtil.getProp("dataformat");
    }

    /**
     * 子类可见的数据输出方法，
     *    将字符串通过Response对象输出到前端
     * @detail:消息内容
     * @response:消息应答对象，通过该对象输出消息内容
     */
    protected void outputContent(String detail,HttpServletResponse response) {
        try {
            response.getWriter().print(detail);
            response.flushBuffer();
        } catch (Exception e) {
        }
    }

    /**
     * 子类可见的数据输出方法，
     *    将对象转换为JSON并用消息格式封装
     * @detail: 消息内容，对象形式
     * @return String Json消息体
     */
    protected String output(Object detail) {
        RspBody result = new RspBody(1, RspBody.SUMESSAGE, detail);
        return result.toJson();
    }

    /**
     * 子类可见的数据输出方法，
     * @return String Json消息体
     */
    protected String output() {
        return this.output(null);
    }

    /**
     * 子类可见的请求数据获取方法
     * @request: 请求
     * @return String 参数内容
     */
    public String getInputString(HttpServletRequest request){
        try {
            InputStream in = request.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(in, CONSTANTS.UTF8));
            StringBuffer buffer = new StringBuffer();
            char[] buff = new char[2048];
            int bytesRead;
            while (-1 != (bytesRead = bf.read(buff, 0, buff.length))) {
                buffer.append(buff, 0, bytesRead);
            }
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 请求数据获取方法
     * @request: 请求
     * @return Map 参数
     */
    public Map getInputJSON(HttpServletRequest request) {
        Map mp = new HashMap();
        try {
            return JSONParser.json2Map( this.getInputString(request) );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mp;
    }

    protected void putCookie(String key, String value, HttpServletResponse resp) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(60 * 60 * 24);
        cookie.setPath("/");
        resp.addCookie(cookie);
    }

    protected Map getInputParam() {
        return (Map) ThreadVariable.getInstance().get("_INPUT_DATA");
    }


    public void putInputParam(Map param) {
        ThreadVariable.getInstance().put("_INPUT_DATA", param);
    }


    /**
     * 获取Code内容
     *
     * @return String
     */
    protected String getInputCode() {
        Map inputParam = getInputParam();
        return (String) inputParam.get("CODE");
    }

    /**
     * 获取DATA内容
     *
     * @return Map
     */
    public Map getInputData() {
        Map inputParam = getInputParam();
        if (inputParam == null || !inputParam.containsKey("DATA")) {
            return new HashMap<>(2);
        } else {

            return (Map) inputParam.get("DATA");
        }

    }


    protected String formatString4Export(String v){
        return new StringBuilder("%").append(v).append("%").toString();
    }

    /**
     * 获取url上面的参数  前端% 传%25
     *
     * @param queryString
     * @return
     * @throws UnsupportedEncodingException
     */
    public Map getUrlSearchData(String queryString) throws UnsupportedEncodingException {

        Map inputData = new HashMap(2);
        if (StringUtils.isNotEmpty(queryString)) {
            String[] querys = URLDecoder.decode(queryString, "UTF-8").split("&");
            for (String query : querys) {
                String[] param = query.split("=");
                String[] params = param[1].split(",");
                if (params != null && params.length > 0) {
                    List list = new ArrayList() {{
                        for (String param : params) {
                            add(param);
                        }
                    }};
                    inputData.put(param[0], list);
                } else {
                    inputData.put(param[0], param[1]);
                }

            }
        }
        return inputData;
    }


}
